package com.lin.export;

import com.alibaba.excel.EasyExcel;
import com.lin.entity.Person;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@RestController
public class ExportController {
    /**
     * 文件下载（失败了会返回一个有部分数据的Excel）
     * <p>
     * 1. 创建excel对应的实体对象 参照{@link DownloadData}
     * <p>
     * 2. 设置返回的 参数
     * <p>
     * 3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @GetMapping("/export")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("导出数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Person.class).sheet("模板").doWrite(data());
    }

    private List<Person> data() {
        List<Person> list = new ArrayList<>();
        Person p1 = new Person();
        p1.setId(1L);
        p1.setDoubleData(1.1);
        p1.setCardNum("35131535313X");
        p1.setPerAge(12);
        p1.setPerBirth(new Date());
        p1.setPhoneNum(18120997089L);

        Person p2 = new Person();
        p2.setId(2L);
        p2.setDoubleData(1.2);
        p2.setCardNum("35131535313X");
        p2.setPerAge(12);
        p2.setPerBirth(new Date());
        p2.setPhoneNum(18120997089L);

        Person p3 = new Person();
        p3.setId(3L);
        p3.setDoubleData(1.3);
        p3.setCardNum("35131535313X");
        p3.setPerAge(12);
        p3.setPerBirth(new Date());
        p3.setPhoneNum(18120997089L);

        list.add(p1);
        list.add(p2);
        list.add(p3);
        return list;
    }
}
